package de.ubschmidt.capi;

import de.ubschmidt.capi.util.Bits;
import java.nio.ByteBuffer;

public class Flags
        implements ByteBufferWritable {

    private short _flags = 0;

    public Flags() {
    }

    Flags(final short flags) {
        _flags = flags;
    }

    public void setFlag(final Flag flag) {
        _flags = (short) Bits.setBit(_flags, flag.getValue());
    }

    public void clearAll() {
        _flags = 0;
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append(getClass().getSimpleName());
        sb.append("[");

        Flag [] flag = Flag.values();
        boolean needSeparator = false;

        for (int i = 0; i < flag.length; ++i) {
            if (Bits.isBitSet(_flags, flag[i].getValue())) {
                if (needSeparator) {
                    sb.append(" ");
                }

                sb.append(flag[i]);
                needSeparator = true;
            }
        }

        sb.append("]");

        return sb.toString();
    }

    /** {@inheritDoc} */
    public void writeTo(final ByteBuffer byteBuffer) {
        byteBuffer.putShort(_flags);
    }

}
